package cn.com.nes.common.util;

import com.alibaba.fastjson2.JSONObject;
import okhttp3.*;

import java.io.IOException;

public class BaiduAPI {
	 public static final String API_KEY = "DLSk29rc5bv637CXccwixDer";
	    public static final String SECRET_KEY = "393pOaXsYZxmTj4yvBZWEZvXMONqyyZK";
	    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

	    public static void main(String []args) throws IOException{
	    	JSONObject result = BaiduAPI.checkComment("快乐老家") ;
	        System.out.println(result.toString());
	    }
	    
		public static JSONObject checkComment(String content) throws IOException {
	        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
	        RequestBody body = RequestBody.create( "text="+content,mediaType);
	        Request request = new Request.Builder()
	            .url("https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=" + getAccessToken())
	            .method("POST", body)
	            .addHeader("Content-Type", "application/x-www-form-urlencoded")
	            .addHeader("Accept", "application/json")
	            .build();
	        Response response = HTTP_CLIENT.newCall(request).execute();
	        return JSONObject.parseObject(response.body().string()) ;
	    }
	    
	   
	    private static String getAccessToken() throws IOException {
	        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
	        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
	                + "&client_secret=" + SECRET_KEY);
	        Request request = new Request.Builder()
	                .url("https://aip.baidubce.com/oauth/2.0/token")
	                .method("POST", body)
	                .addHeader("Content-Type", "application/x-www-form-urlencoded")
	                .build();
	        Response response = HTTP_CLIENT.newCall(request).execute();
	        JSONObject object = JSONObject.parseObject(response.body().string()) ;
	        return object.getString("access_token");
	    }
}
